﻿using Generic.Helper.Configure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace Generic.App.EntityFrameworkCore.MigrationHelper;

/// <summary>
/// 设计时 DbContext 创建：https://docs.microsoft.com/zh-cn/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli
/// </summary>
internal class CustomContextFactory : IDesignTimeDbContextFactory<GenericAppContext>
{
    public CustomContextFactory()
    {

    }
    public GenericAppContext CreateDbContext(string[] args)
    {
        var configuration = BuildConfiguration();

        var builder = new DbContextOptionsBuilder<GenericAppContext>()
            .UseSqlServer(configuration.GetConnectionString("GenericAppConnectionStr"));

        IOptions<AesOptions> aesOptions = Options.Create(new AesOptions
        {
            Key = configuration.GetSection("AesSecretKey:Key").Value,
            IV = configuration.GetSection("AesSecretKey:IV").Value
        });

        return new GenericAppContext(builder.Options, aesOptions);
    }

    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../Generic.App.HttpApi.Host/"))
            .AddJsonFile("appsettings.json", optional: false);

        return builder.Build();
    }
}